package com.kyxx.topics.activity;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.kyxx.topics.BaseActivity;
import com.kyxx.topics.BaseApp;
import com.kyxx.topics.R;
import com.kyxx.topics.adapter.AddQuanAdapter;
import com.kyxx.topics.adapter.MemberAddCardAdapter;
import com.kyxx.topics.adapter.OnTextChangeAdapter;
import com.kyxx.topics.adapter.SearchQuanAdapter;
import com.kyxx.topics.bean.AddQuanBean;
import com.kyxx.topics.bean.MemberAddCardBean;
import com.kyxx.topics.decoration.DividerItemDecoration;
import com.kyxx.topics.decoration.TitleItemDecoration;
import com.kyxx.topics.net.LoadingStringCallBack;
import com.kyxx.topics.net.OkGoRequest;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.widget.ClearEditText;
import com.kyxx.topics.widget.IndexBar;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Response;

public class AddYouHuiQuanActivity extends BaseActivity implements View.OnClickListener {
    private ClearEditText et_msg_search;
    private RecyclerView rv_member_add_card;
    private RelativeLayout rl_seach_card_btn;
    LinearLayout ll_add_card;
    RecyclerView rv_searh_card;
    LinearLayout ll_search_card;
    TextView tv_search_cancle;
    private IndexBar indexBar;
    private LinearLayoutManager mManager;
    private List<AddQuanBean> bean = new ArrayList<>();
    private AddQuanAdapter adapter;
    private SearchQuanAdapter searchCardAdapter;

    private final static int NOTIFY = 1;
    Handler mHandler = new Handler() {
        @Override
        public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
            switch (msg.what) {
                case NOTIFY:
                    adapter = new AddQuanAdapter(AddYouHuiQuanActivity.this, bean);
                    rv_member_add_card.setAdapter(adapter);
                    rv_member_add_card.addItemDecoration(new TitleItemDecoration(AddYouHuiQuanActivity.this, bean).setColorTitleBg(0xfff0f0f0).setColorTitleFont(0xff575757));
                    rv_member_add_card.addItemDecoration(new DividerItemDecoration(AddYouHuiQuanActivity.this, DividerItemDecoration.VERTICAL_LIST));
                    //使用indexBar
                    indexBar.setNeedRealIndex(false)//设置需要真实的索引
                            .setmLayoutManager(mManager)//设置RecyclerView的LayoutManager
                            .setmSourceDatas(bean);//设置数据源
//                    .setmPressedShowTextView(tvSideBarHint)//设置HintTextView
                    break;
            }
            return super.sendMessageAtTime(msg, uptimeMillis);
        }
    };

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_add_you_hui_quan);
    }

    @Override
    protected void findViewById() {
        et_msg_search = (ClearEditText) findViewById(R.id.et_msg_search);
        rv_member_add_card = (RecyclerView) findViewById(R.id.rv_member_add_card);
        indexBar = (IndexBar) findViewById(R.id.indexBar);
        ll_add_card = (LinearLayout) findViewById(R.id.ll_add_card);
        rv_searh_card = (RecyclerView) findViewById(R.id.rv_searh_card);
        ll_search_card = (LinearLayout) findViewById(R.id.ll_search_card);
        tv_search_cancle = (TextView) findViewById(R.id.tv_search_cancle);
    }

    @Override
    protected void setListener() {
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        et_msg_search.setOnClickListener(this);
        tv_search_cancle.setOnClickListener(this);
    }

    @Override
    protected void processLogic() {
        getData();
        mManager = new LinearLayoutManager(this);
        rv_member_add_card.setLayoutManager(mManager);
        rv_searh_card.setLayoutManager(new LinearLayoutManager(this));
        et_msg_search.addTextChangedListener(new OnTextChangeAdapter() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.et_msg_search:
                ll_add_card.setVisibility(View.GONE);
                ll_search_card.setVisibility(View.VISIBLE);
                tv_search_cancle.setVisibility(View.VISIBLE);
                break;
            case R.id.tv_search_cancle:
                ll_add_card.setVisibility(View.VISIBLE);
                ll_search_card.setVisibility(View.GONE);
                tv_search_cancle.setVisibility(View.GONE);
                et_msg_search.setText("");
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                break;
        }
    }

    private void getData() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uid", BaseApp.getModel().getId());
        HttpParams params = new HttpParams();
        params.put("json", jsonObject.toString());
        OkGoRequest.post(UrlUtils.GETALLCOUPON, this, "getallcoupon", CacheMode.REQUEST_FAILED_READ_CACHE, params, new LoadingStringCallBack(AddYouHuiQuanActivity.this,true) {
            @Override
            public void onCacheSuccess(String s, Call call) {
                super.onCacheSuccess(s, call);
                onSuccess(s, call, null);
            }

            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    org.json.JSONObject result = new org.json.JSONObject(s);
                    bean = JSONObject.parseArray(result.getJSONArray("data").toString(), AddQuanBean.class);
                    mHandler.sendEmptyMessage(NOTIFY);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<AddQuanBean> filterDateList = new ArrayList<>();

        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = bean;
        } else {
            filterDateList.clear();
            for (AddQuanBean sortModel : bean) {
                String name = sortModel.getTitle();
                String namepinyin = sortModel.getMemberCardPinyin();
                if (name.indexOf(filterStr.toString()) != -1
                        || namepinyin.toLowerCase().contains(filterStr.toString().toLowerCase())
                        || name.toLowerCase().contains(filterStr.toString().toLowerCase())) {
                    filterDateList.add(sortModel);
                }
            }
        }
        searchCardAdapter = new SearchQuanAdapter(context, filterDateList);
        rv_searh_card.setAdapter(searchCardAdapter);
    }
}
